#include "refbase.h"
#include "log.h"

RefBase::RefBase()
{
    counter = new WeakRefCounter();
    counter->obj = this;
}

void RefBase::StrongRefCountIncrease()
{
    DEBUG_LOG("sref: %d -> %d, %p", strongRefCount, strongRefCount + 1, this);
    strongRefCount++;
}

void RefBase::StrongRefCountDecrease()
{
    DEBUG_LOG("sref: %d -> %d, %p", strongRefCount, strongRefCount - 1, this);
    strongRefCount--;
    if (strongRefCount == 0) {
        if (counter->weakRefCount == 0) {
            DEBUG_LOG("delete counter %p", this);
            delete counter;
        } else {
            DEBUG_LOG("nullptr counter %p", counter);
            counter->obj = nullptr;
        }
        DEBUG_LOG("strong delete %p", this);
        delete this;
    }
}

WeakRefCounter *RefBase::GetWeakRefCounter() const
{
    return counter;
}

void WeakRefCounter::WeakRefCountIncrease()
{
    DEBUG_LOG("wref: %d -> %d, %p", weakRefCount, weakRefCount + 1, this);
    weakRefCount++;
}

void WeakRefCounter::WeakRefCountDecrease()
{
    DEBUG_LOG("wref: %d -> %d, %p", weakRefCount, weakRefCount - 1, this);
    weakRefCount--;
    if (weakRefCount == 0) {
        DEBUG_LOG("wptr delete %p", this);
        delete this;
    }
}

RefBase *WeakRefCounter::GetRefPtr() const
{
    return obj;
}
